package com.android.boncen.commonFrame.user;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;

import com.android.boncen.commonFrame.R;
import com.android.boncen.commonFrame.adapter.GluciseAdapter;
import com.android.boncen.commonFrame.bean.GlucoseHistoryBean;
import com.android.boncen.commonFrame.tools.DesityUtil;

import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;

/**
 * 功能描述:血糖历史-分页处理ok
 *
 * @date 2017/2/9
 */

public class GlucoseHistoryFragment extends Fragment {

    private ListView lvList;
    private GluciseAdapter adapter;
    private int page = 1;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.comm_list_layout, container, false);
        lvList = (ListView) view.findViewById(R.id.lvList);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        adapter = new GluciseAdapter(getContext());
        lvList.setAdapter(adapter);
        lvList.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                // 当不滚动时
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    // 判断是否滚动到底部
                    if (view.getLastVisiblePosition() == view.getCount() - 1) {
                        //加载更多功能的代码
                        page++;
                        getGlucoseHistoryBean(page);
                    }
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });
        getGlucoseHistoryBean(page);
    }

    public void getGlucoseHistoryBean(int page) {
        BmobUser user = BmobUser.getCurrentUser();
        BmobQuery<GlucoseHistoryBean> query = new BmobQuery<GlucoseHistoryBean>();
        query.addWhereEqualTo("userId", user.getObjectId());    // 查询当前用户的所有
        query.addWhereEqualTo("typeBlood", 0);
        query.order("-updatedAt");
        query.setSkip(20 * (page - 1));
        query.setLimit(20);
        query.findObjects(new FindListener<GlucoseHistoryBean>() {

            @Override
            public void done(List<GlucoseHistoryBean> object, BmobException e) {
                if (e == null) {
                    adapter.setData(object);
                } else {

                }
            }

        });
    }
}
